import re
from collections import defaultdict

# 输入日志字符串
log_strings = """
[2023-05-01 08:30:45] GET /index.html HTTP/1.1 200
[2023-05-01 08:31:02] POST /login HTTP/1.1 302
[2023-05-01 08:35:18] GET /profile HTTP/1.1 200
[2023-05-01 08:37:45] GET /index.html HTTP/1.1 404
[2023-05-01 08:38:00] POST /logout HTTP/1.1 500
"""

# 定义日志解析函数
def parse_log_line(line):
    """解析单行日志，提取关键信息"""
    pattern = r'\[(.*?)\] (.*?) (.*?) HTTP/1.1 (\d{3})'
    match = re.match(pattern, line)
    if match:
        timestamp, method, path, status_code = match.groups()
        return {
            'timestamp': timestamp,
            'method': method,
            'path': path,
            'status_code': int(status_code)
        }
    return None

# 解析日志字符串
log_lines = log_strings.strip().split('\n')
parsed_logs = [parse_log_line(line) for line in log_lines if parse_log_line(line)]

# 输出解析后的字典列表
print("解析后的字典列表：")
print(parsed_logs)

# 状态码统计字典
status_code_count = defaultdict(int)
for log in parsed_logs:
    status_code_count[log['status_code']] += 1

print("\n状态码统计字典：")
print(dict(status_code_count))

# 最频繁路径
path_count = defaultdict(int)
for log in parsed_logs:
    path_count[log['path']] += 1

most_frequent_path = max(path_count, key=path_count.get)

print("\n最频繁路径：")
print(most_frequent_path)

# 异常请求列表（假设状态码 4xx 和 5xx 为异常请求）
error_status_codes = [400, 401, 403, 404, 500, 502, 503, 504]
error_requests = [log for log in parsed_logs if log['status_code'] in error_status_codes]

print("\n异常请求列表：")
print(error_requests)